﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Serialization;


namespace CCPSIP.iBeacon
{
    /// <summary>列出掃到的多個Beacon的Rules</summary>

    public class Rules_List : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string[] Major = req.Form["Major"].Split(',');
                string[] Minor = req.Form["Minor"].Split(',');
                string[] Proximity = req.Form["Proximity"].Split(',');

                //【02】驗證Major, Minor, Proximity數目是否相等
                if (Major.Length != Minor.Length || Major.Length != Proximity.Length)
                    throw new Exception("Error01: The count of major, minor and proximity does not match."); //Major和Minor數目不相等

                //【03】驗證使用者身分
                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                    throw new Exception("ERROR_02: Cannot identify this device."); //無法識別此裝置

                //【04】取得符合條件的Rules
                List<List<Rule>> MultiBeaconRuleList = new List<List<Rule>>();
                for (int i = 0; i < Major.Length; i++)
                {
                    //【04-1】驗證iBeacon是否存在
                    if (!iBeaconKit.IsBeaconExist(Major[i], Minor[i]))
                        continue;
                    //throw new Exception("ERROR_03: iBeacon does not exist or not activate, major = " + Major[i] + " minor = " + Minor[i]); //此iBeacon不存在資料庫中或未啟用

                    //【04-2】取得指定Beacon的Rule
                    List<Rule> BeaconRuleList = iBeaconKit.GetRuleList(Major[i], Minor[i], Proximity[i]);

                    //【04-3】取得符合權限的Rule
                    List<Rule> HasRightRuleList = iBeaconKit.GetRuleList(userInfo);

                    //【04-4】取得交集Rule
                    List<Rule> TempRuleList = new List<Rule>();
                    foreach (Rule r1 in BeaconRuleList)
                    {
                        foreach (Rule r2 in HasRightRuleList)
                        {
                            if (r1.RuleName.Equals(r2.RuleName))
                                TempRuleList.Add(r1);
                        }
                    }

                    //【04-5】檢查Rule是否符合Repeat_Schedule規則
                    TempRuleList = iBeaconKit.CheckRepeatSchedule(TempRuleList);

                    //【04-6】將Rule加入MultiBeaconRuleList中
                    MultiBeaconRuleList.Add(TempRuleList);
                }

                //【05】取得每個Beacon的Rule聯集
                List<Rule> ReturnRuleList = new List<Rule>();
                foreach (List<Rule> RL in MultiBeaconRuleList)
                {
                    foreach (Rule rl in RL)
                    {
                        if (!ReturnRuleList.Contains(rl))
                            ReturnRuleList.Add(rl);
                    }
                }

                //【98】序列化Rule物件
                JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
                resultStr = JsonSerializer.Serialize(ReturnRuleList);

                //【99】回傳Json
                context.Response.ContentType = "application/json";
                context.Response.Charset = null;
                context.Response.Write(resultStr);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex)
            {
                //【99】回傳Xml
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
                context.Response.Charset = null;
                context.Response.Write(resultStr);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}